package com.blog.service.comment.impl;

import com.blog.constant.ErrorConstant;
import com.blog.dto.cond.CommentCondition;
import com.blog.exception.BusinessException;
import com.blog.mapper.CommentMapper;
import com.blog.model.Comment;
import com.blog.model.Content;
import com.blog.service.comment.CommentService;
import com.blog.service.content.ContentService;
import com.blog.utils.MethodUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 评论服务层的业务接口实现类
 *
 * @author wmb
 *
 * @since 2021-2-9
 */
@Service("commentService")
@Transactional
public class CommentServiceImpl implements CommentService {

    private static final Map<String, String> STATUS_MAP = new ConcurrentHashMap<>();

    /**
     * 评论状态：正常
     */
    private static final String STATUS_NORMAL = "approved";
    /**
     * 评论状态：不显示
     */
    private static final String STATUS_BLANK = "not_audit";

    static {
        STATUS_MAP.put("approved", STATUS_NORMAL);
        STATUS_MAP.put("not_audit", STATUS_BLANK);
    }

    @Autowired
    @Qualifier("commentMapper")
    private CommentMapper commentMapper;

    @Autowired
    @Qualifier("contentService")
    private ContentService contentService;

    /**
     * 根据文章编号获取评论列表--只显示通过审核的评论-正常状态的
     *
     * @param cid 文章主键编号
     *
     * @return
     */
    @Override
    @Cacheable(value = "commentCache", key = "'commentsByCId_' + #p0")
    public List<Comment> getCommentsByCId(Integer cid) {
        return commentMapper.getCommentsByCid(cid);
    }

    /**
     * 新增评论
     *
     * @param comment 评论的实体
     *
     * @return
     */
    @Override
    @CacheEvict(value="commentCache", allEntries=true)
    public void saveComment(Comment comment) {
        if (comment == null) {
            throw new BusinessException(ErrorConstant.PARAM_IS_NULL, MethodUtil.getLineInfo());
        }

        Content content = contentService.getArticleById(comment.getCid());
        if (content == null) {
            throw new BusinessException(ErrorConstant.CONTENT_IS_NOT_EXISTS, MethodUtil.getLineInfo());
        }
        comment.setOwnerId(content.getAuthorId());
        comment.setStatus(STATUS_MAP.get(STATUS_BLANK));

        commentMapper.saveComment(comment);

        // 文章评论数+1
        Integer count = content.getCommentsNum();
        if (count == null) {
            count = 0;
        }
        content.setCommentsNum(count + 1);
        contentService.updateArticleByCid(content);
    }

    /**
     * 根据条件获取评论列表
     *
     * @param commentCondition 查询条件
     * @param pageNum 分页参数 第几页
     * @param pageSize 分页参数 每页条数
     *
     * @return
     */
    @Override
    @Cacheable(value = "commentCache", key = "'commentsByCond_' + #p1")
    public PageInfo<Comment> getCommentsByCondition(CommentCondition commentCondition, Integer pageNum, Integer pageSize) {
        if (commentCondition == null) {
            throw new BusinessException(ErrorConstant.COMMENT_IS_NOT_EXISTS, MethodUtil.getLineInfo());
        }

        PageHelper.startPage(pageNum, pageSize);
        List<Comment> commentList = commentMapper.getCommentsByCondition(commentCondition);
        return new PageInfo<>(commentList);
    }

    /**
     * 查找单条评论
     *
     * @param id
     *
     * @return
     */
    @Override
    public Comment getCommentById(Integer id) {
        return commentMapper.getCommentById(id);
    }

    /**
     * 删除评论
     *
     * @param id 评论的主键编号
     *
     * @return
     */
    @Override
    @CacheEvict(value="commentCache",allEntries=true)
    public void deleteCommentById(Integer id) {
        // 查看是否已被删除
        Comment comment = commentMapper.getCommentById(id);
        if (comment == null) {
            throw new BusinessException(ErrorConstant.DELETE_COMMENT_FAILED_COMMENT_IS_NOT_EXISTS, MethodUtil.getLineInfo());
        }

        // 查看删除的评论存在子评论，一并删除
        // 查找当前评论是否有子评论
        CommentCondition commentCondition = new CommentCondition();
        commentCondition.setParent(id);
        List<Comment> childCommentList = commentMapper.getCommentsByCondition(commentCondition);
        Integer count = 0;
        // 删除子评论
        if (CollectionUtils.isNotEmpty(childCommentList)) {
            for (Comment childComment: childCommentList) {
                commentMapper.deleteCommentById(childComment.getId());
                count++;
            }
        }
        // 删除当前评论
        commentMapper.deleteCommentById(id);
        count++;

        // 更新当前文章的评论数
        Content content = contentService.getArticleById(comment.getCid());
        if (content != null && content.getCommentsNum() != null && content.getCommentsNum() > 0) {
            content.setCommentsNum(content.getCommentsNum() - count);
            contentService.updateArticleByCid(content);
        }
    }

    /**
     * 更新评论的状态
     *
     * @param id 评论的主键编号
     * @param status 状态
     *
     * @return
     */
    @Override
    @CacheEvict(value="commentCache", allEntries=true)
    public void updateCommentStatus(Integer id, String status) {
        commentMapper.updateCommentStatus(id, status);
    }
}
